import axios from 'axios'

import {userStore} from '@/stores/user'
// 创建axios实例
const http = axios.create({
  baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net',
  timeout: 5000
})

// axios请求拦截器
http.interceptors.request.use(config => {

  const userstore= userStore()
  const token =userstore.userinfo.token
  if(token){
    //存到请求头里
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
}, e => Promise.reject(e))

// axios响应式拦截器
http.interceptors.response.use(res => res.data, e => {
  const userstore = userStore()

  // 弹出提示框
  ElMessage({
    type: 'warning',
    message: e.response.data.message
  })
  if(e.response.status===401){
    userstore.clearlogin()
    router.push('/login')
  }
  return Promise.reject(e)
})

export default http
